import { isDate, isObject, isURLSearchParams } from './utils';
interface URLOrigin {
  protocol: string;
  host: string;
}
function encode(val: string): string {
  return encodeURIComponent(val)
    .replace(/%40/g, '@')
    .replace(/%3A/gi, ':')
    .replace(/%24/g, '$')
    .replace(/%2C/gi, ',')
    .replace(/%20/g, '+')
    .replace(/%5B/gi, '[')
    .replace(/%5D/gi, ']');
}

export function isAbsoluteURL(url: string): boolean {
  return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
}

export function combineURL(baseURL: string, relativeURL?: string): string {
  return relativeURL
    ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
    : baseURL;
}

export function buildURL(
  url: string,
  params?: any,
  paramsSeralizer?: (params: any) => string
): string {
  if (!params) {
    return url;
  }
  let serializeParams;
  if (paramsSeralizer) {
    serializeParams = paramsSeralizer(params);
  } else if (isURLSearchParams(params)) {
    serializeParams = params.toString();
  } else {
    const parts: string[] = [];

    Object.keys(params).forEach(key => {
      const val = params[key];
      if (val === null || val === undefined) {
        return;
      }
      let values = [];
      if (Array.isArray(val)) {
        values = val;
        key += '[]';
      } else {
        values = [val];
      }
      values.forEach(value => {
        if (isDate(value)) {
          value = value.toISOString();
        } else if (isObject(value)) {
          value = JSON.stringify(value);
        }
        parts.push(`${encode(key)}=${encode(value)}`);
      });
    });
    serializeParams = parts.join('&');
  }

  if (serializeParams) {
    const markIndex = url.indexOf('#');
    if (markIndex > -1) {
      url = url.slice(0, markIndex);
    }
    url += (url.indexOf('?') > -1 ? '&' : '?') + serializeParams;
  }
  return url;
}

export function isURLSameOrigin(requestURL: string): boolean {
  const requestOrigin = resolveOrigin(requestURL);
  return (
    requestOrigin.protocol === currentOrigin.protocol && requestOrigin.host === currentOrigin.host
  );
}

const urlParsingNode = document.createElement('a');
const currentOrigin = resolveOrigin(window.location.href);
function resolveOrigin(url: string): URLOrigin {
  urlParsingNode.setAttribute('href', url);
  const { protocol, host } = urlParsingNode;
  return {
    protocol,
    host,
  };
}
